#include <iostream>
#include "igslib_iutil.h"
#include "igslib_iserial_manager.h"
#include "igslib_igpio.h"
#include "igslib_ibutton.h"

namespace igslib
{
    namespace button_sample
    {
        static void GPIOButton()
        {
            const int size = 12;

            ISerialManager* srm = GetSerialManagerInstance();
            ISpi* spi = srm->New_ProjMCU_spi("DragonBallRace");
            spi->SetWorkingFrequency(10000000);
            bool open_result = spi->Open(ISpi::cs0);
            if (open_result == false)
            {
                throw_igslib_exception("Open SPI Node fail.");
            }

            IGPIOManager* gpio_mgr = GetGPIOManagerInstance();
            IButtonManager* btn_mgr = GetButtonManagerInstance();
            std::vector<IButton*> buttons;
            for ( int i = 0 ; i < size ; ++i )
            {
                IGPIO* gpio = gpio_mgr->New_ProjMCU("M01_TestPattern");
                gpio->SetMode(IGPIO::mode::input);
                gpio->SetNumber(i);
                gpio->SetSPI(spi);

                IGPIOButton* btn = btn_mgr->NewGPIOButton();
                btn->SetGPIO(gpio);

                std::stringstream ss;
                ss << "gpio_btn_" << i;
                btn->SetName(ss.str());

                buttons.push_back(btn);
            }
            while(util::KbHit() != 27)
            {
                for(auto& each:buttons)
                {
                    if (each->IsPressed())
                    {
                        util::Log("%s> %s pressed.\n",__func__,each->GetName().c_str());
                    }
                    if (each->IsPressDown())
                    {
                        util::Log("%s> %s pressdown.\n",__func__,each->GetName().c_str());
                    }
                }
                btn_mgr->Update();
                spi->Update();
                util::SleepMSTime(16);
            }
            exit(EXIT_SUCCESS);
        }
    };
};
